package com.laicunba.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.laicunba.pojo.PicDO;
import com.laicunba.service.PicService;
import com.laicunba.util.StringUtil;

@Service
public class PicServiceFtpImpl extends BaseServiceImpl implements PicService {
	private static final Logger LOG = Logger.getLogger(PicServiceFtpImpl.class);

	@Value("${ftp.host:v0.ftp.upyun.com}")
	private String ftpHost;
	@Value("${ftp.username:a110110110/laicunba}")
	private String ftpUserName;
	@Value("${ftp.password:jmdjsj903291903291}")
	private String ftpPassword;
	@Value("${ftp.dir:/resource/}")
	private String ftpDir;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH/mm");

	@Override
	public PicDO createNewFile(DiskFileItem fileItem) {

		try {
			PicDO picDO = new PicDO();
			String names[] = fileItem.getName().split("[\\.]");
			String newFileName = sdf.format(new Date()) + "/" + StringUtil.genGUID() + "." + names[names.length - 1];

			upload2Ftp(fileItem.getInputStream(), ftpDir + newFileName);
			picDO.setPath(newFileName);
			picDO.setSize(fileItem.getSize());
			picDO.setName(fileItem.getName());
			picDO.setContentType(fileItem.getContentType());
			create(picDO);
			return picDO;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void upload2Ftp(InputStream inputStream, String destPath) {
		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(ftpHost);
			ftp.login(ftpUserName, ftpPassword);
			ftp.mkd(destPath.substring(0, destPath.lastIndexOf("/")));
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.storeFile(destPath, inputStream);
		} catch (Exception e) {
			LOG.error("upload2ftp error", e);
		} finally {
			try {
				ftp.disconnect();
			} catch (IOException e) {
			}
		}

	}

}
